<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <!-- 搜索表单 -->
        <el-form
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="房号" prop="roomInfo.infoId">
            <el-input
              id="infoId"
              v-model="queryParams.infoId"
              placeholder="请输入房间号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="房型" prop="roomInfo.infoName">
            <el-select
              id="infoName"
              v-model="queryParams.infoName"
              clearable
              placeholder="请选择"
              @keyup.enter.native="handleQuery"
            >
              <el-option
                v-for="item in roomTypeOptions"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeName"
                @keyup.enter.native="handleQuery"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="楼层" prop="roomInfo.infoFloor">
            <el-input
              id="infoFloor"
              v-model="queryParams.infoFloor"
              placeholder="请输入房间楼层"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="入住时间" prop="roomStatus.inTime">
            <el-date-picker
              v-model="queryParams.inTime"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-ddTHH:mm:ss.SSSZ"
              :picker-options="inTimeOptions"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="退房时间" prop="roomStatus.outTime">
            <el-date-picker
              v-model="queryParams.outTime"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-ddTHH:mm:ss.SSSZ"
              :picker-options="outTimeOptions"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              v-hasAuthority="['pos:order:list']"
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <!-- 数据操作按钮 -->
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" size="small" @click="showTable"
              >入住</el-button
            >
            <el-button type="primary" size="small" @click="showQuantity"
              >可用房型和数量</el-button
            >
          </el-col>
        </el-row>

        <!-- 数据展示Table -->
        <el-table v-if="showTable1" v-loading="loading" :data="dataList">
          <el-table-column prop="roomInfo.infoId" label="房号" width="140" />
          <el-table-column prop="roomInfo.infoName" label="房型" width="120" />
          <el-table-column prop="roomInfo.infoFloor" label="楼层" />
          <el-table-column prop="roomStatus.inTime" label="入住时间" />
          <el-table-column prop="roomStatus.outTime" label="退房时间" />
          <el-table-column prop="roomType.typePrice" label="价格" />
          <el-table-column prop="roomStatus.roomStatus" label="状态" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                v-hasAuthority="['pos:roomOrder:add']"
                size="small"
                type="text"
                @click="addStatics(scope.row)"
                >入住</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页加载 -->
        <el-pagination
          v-if="showTable1"
          :page-sizes="[5, 10, 20, 50]"
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          layout="total,sizes,prev,pager,next,jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>

    <!-- 新增数量对话框 默认不显示 -->
    <el-dialog
      :visible.sync="openOne"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="formOne"
        :model="formOne"
        :rules="ruleOne"
        label-width="80px"
      >
        <el-form-item label="顾客人数" prop="cusQuantity">
          <el-input
            v-model="formOne.cusQuantity"
            placeholder="请输顾客人数"
            type="number"
            @keyup.enter.native="submitFormOne"
          />
        </el-form-item>
        <el-form-item label="房间数量" prop="roomQuantity">
          <el-input
            v-model="formOne.roomQuantity"
            placeholder="请输入房间数量"
            type="number"
            @keyup.enter.native="submitFormOne"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormOne()">添加</el-button>
        <el-button @click="cancelOne">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增信息对话框 -->
    <el-dialog
      :visible.sync="openTwo"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="formTwo"
        :model="formTwo"
        :rules="ruleTwo"
        label-width="80px"
      >
        <el-form-item label="房间类型" prop="roomType">
          <el-input v-model="formTwo.roomType" placeholder="请输房间类型" />
        </el-form-item>
        <el-form-item label="房型号" prop="typeId">
          <el-input
            v-model="formTwo.typeId"
            placeholder="请输要预定的房型号"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="房间号" prop="infoId" v-show="this.showTable1">
          <el-input v-model="formTwo.infoId" placeholder="请输顾客房间号" />
        </el-form-item>
        <el-form-item label="顾客ID" prop="cusId" name="">
          <el-input v-model="formTwo.cusId" placeholder="请输顾客ID" />
        </el-form-item>
        <el-form-item label="顾客姓名" prop="cusName">
          <el-input v-model="formTwo.cusName" placeholder="请输顾客姓名" />
        </el-form-item>
        <el-form-item label="顾客电话" prop="cusPhoneNum">
          <el-input v-model="formTwo.cusPhoneNum" placeholder="请输顾客电话" />
        </el-form-item>
        <el-form-item label="顾客性别" prop="cusSex">
          <el-input v-model="formTwo.cusSex" placeholder="请输顾客性别" />
        </el-form-item>
        <el-form-item label="入住时间" prop="inTime">
          <el-input v-model="formTwo.inTime" placeholder="请输入住时间" />
        </el-form-item>
        <el-form-item label="退房时间" prop="outTime">
          <el-input v-model="formTwo.outTime" placeholder="请输退房时间" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="formTwo.price" placeholder="请输价格" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormTwo">添加</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancelTwo">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看可用房型和数量 -->
    <el-table v-if="showTable2" v-loading="loading" :data="tableData">
      <el-table-column prop="typeId" label="房型ID" width="300" />
      <el-table-column prop="typeName" label="房型" width="300" />
      <el-table-column prop="typeNum" label="可用数量" width="300" />
      <el-table-column prop="typePrice" label="价格" width="300" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            v-hasAuthority="['pos:roomOrder:add']"
            size="small"
            type="text"
            @click="addStatics(scope.row)"
            >预定</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {
  listroomOrderByPage,
  makeNewOrder,
  enterOrder,
  endEnter,
  selectTypeNum,
} from "@/api/pos/roomOrder";
import { listAllRoomType } from "@/api/pos/roomType";
import Item from "@/layout/components/Sidebar/Item.vue";
import moment from "moment";
export default {
  name: "RoomOrder",
  // 定义属性
  data() {
    return {
      //入住和预定时将价格回显到表格
      TypePrice: 0,
      RoomType: null,
      // 设置时间限制
      inTimeOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      // 可用房型和数量
      showTable1: true,
      showTable2: false,
      roomTypes: [],
      quantities: [],
      prices: [],
      tableData: [],
      // 入住时间
      value1: "",
      // 遮罩层
      loading: false,
      dataList: [],
      roomTypeOptions: [],
      typeIdInput: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        infoId: null,
        infoName: null,
        roomStatus: null,
        infoFloor: null,
        typeId: null,
        typeName: null,
        typePrice: null,
        inTime: null,
        outTime: null,
      },
      multiple: true,
      // 总条数:
      total: 0,
      // 对话框是否显示
      openTable: true,
      openQuantity: false,
      openOne: false,
      openTwo: false,
      openThree: false,

      // 表单1数据
      formOne: {},
      formTwo: {},
      formThree: {},
      // 表单校验规则
      ruleOne: {
        cusQuantity: [
          { required: true, message: "顾客数量不能为空", trigger: "blur" },
        ],
        roomQuantity: [
          { required: true, message: "房间不能数量为空", trigger: "blur" },
        ],
      },
      ruleTwo: {
        typeId: [
          { required: true, message: "房型id不能为空", trigger: "blur" },
        ],
        roomType: [
          { required: true, message: "房间类型不能为空", trigger: "blur" },
        ],
        cusId: [
          { required: true, message: "顾客ID不能为空", trigger: "blur" },
          { validator: this.validatorNumber, trigger: "blur" },
        ],
        cusName: [
          { required: true, message: "顾客姓名不能为空", trigger: "blur" },
        ],
        cusPhoneNum: [
          { required: true, message: "顾客电话不能为空", trigger: "blur" },
          { validator: this.validatePhone, trigger: "blur" },
        ],
        cusSex: [
          { required: true, message: "顾客性别不能为空", trigger: "blur" },
          { validator: this.validateSex, trigger: "blur" },
        ],
        infoId: [
          { required: true, message: "房间号不能为空", trigger: "blur" },
        ],
        inTime: [
          { required: true, message: "入住时间不能为空", trigger: "blur" },
        ],
        outTime: [
          { required: true, message: "退房时间不能为空", trigger: "blur" },
        ],
        price: [
          { required: true, message: "房间价格不能为空", trigger: "blur" },
        ],
      },
    };
  },
  // 计算属性，可选
  computed: {
    //设置退房时间
    outTimeOptions() {
      return {
        disabledDate: this.outTimeDisabledDate,
      };
    },
  },
  // 监控data变化，可选
  watch: {},

  // 生命周期-创建完成，可选
  created() {
    //this.showQuantity()
  },
  // 生命周期-挂载完成，可选
  mounted() {
    this.getList();
    this.getroomTypeOptions();
  },

  // 方法集合
  methods: {
    getList() {
      this.loading = true;
      listroomOrderByPage(this.queryParams).then((response) => {
        this.dataList = response.data.list;
        // 将后端传回来的时间换一个格式
        for (let index = 0; index < this.dataList.length; index++) {
          if (this.dataList[index].roomStatus.inTime) {
            this.dataList[index].roomStatus.inTime = this.dataList[
              index
            ].roomStatus.inTime.slice(0, 10);
          }
        }
        for (let index = 0; index < this.dataList.length; index++) {
          if (this.dataList[index].roomStatus.outTime) {
            this.dataList[index].roomStatus.outTime = this.dataList[
              index
            ].roomStatus.outTime.slice(0, 10);
          }
        }
        this.loading = false;
      });
    },
    // 显示可用房型和数量
    showQuantity() {
      this.showTable1 = false;
      this.showTable2 = true;
      selectTypeNum(this.queryParams).then((response) => {
        this.tableData = response.data;
      });
    },
    // /** 搜索按钮操作 */
    handleQuery() {
      if (this.showTable1) {
        this.getList();
      } else if (this.showTable2) {
        console.log(this.queryParams);
        selectTypeNum(this.queryParams).then((response) => {
          console.log(response.data);
          this.tableData = response.data;
        });
      }
    },
    // /** 重置按钮操作 */
    resetQuery(queryForm) {
      this.queryParams.infoId = null;
      this.queryParams.infoName = null;
      this.queryParams.infoFloor = null;
      this.queryParams.inTime = null;
      this.queryParams.outTime = null;
      if (this.showTable1) {
        this.getList();
      } else if (this.showTable2) {
        this.showQuantity();
      }
    },
    // 初始化表单
    resetformOne() {
      this.formOne = {
        roomQuantity: 0,
        cusQuantity: 0,
      };
    },
    resetformTwo() {
      this.formTwo = {
        roomType: "",
        cusId: 0,
        cusName: "",
        cusPhoneNum: 0,
        cusSex: "",
        infoId: 0,
        inTime: "",
        outTime: "",
        price: this.TypePrice,
      };
    },
    // 点击入住和预定按钮显示数量的表单
    addStatics(row) {
      const { inTime, outTime } = this.queryParams;
      if (!inTime || !outTime) {
        this.$message.error("请先填写入住时间和退房时间！");
      } else {
        if (this.showTable1) {
          this.TypePrice = row.roomType.typePrice;
          this.RoomType = row.roomInfo.infoName;
          this.RoomInfoId = row.roomInfo.infoId;
          // console.log(row.roomInfo.infoName);
          // console.log(this.RoomType);
        } else if (this.showTable2) {
          this.TypePrice = row.typePrice;
          this.RoomType = row.typeName;
        }
        //console.log(price);
        this.resetformOne();
        this.openOne = true;
      }
    },
    // 返回数量并显示信息的表单
    submitFormOne() {
      this.formOne.cusQuantity = parseInt(this.formOne.cusQuantity);
      this.formOne.roomQuantity = parseInt(this.formOne.roomQuantity);
      makeNewOrder(this.formOne).then((response) => {
        this.$message.success(response.msg);
        this.cancel;
        this.resetformTwo();
        // 把上面的时间回显到表格里
        const intTimeOne = moment(this.queryParams.inTime);
        const inTime = intTimeOne.format("YYYY-MM-DD");
        const outTimeOne = moment(this.queryParams.outTime);
        const outTime = outTimeOne.format("YYYY-MM-DD");
        this.formTwo.inTime = inTime;
        this.formTwo.outTime = outTime;
        this.formTwo.roomType = this.RoomType;
        if (this.showTable1) {
          this.formTwo.infoId = this.RoomInfoId;
        }

        if (this.RoomType == "大床房") {
          this.formTwo.typeId = 1;
        } else if (this.RoomType == "豪华大床房") {
          this.formTwo.typeId = 2;
        } else if (this.RoomType == "双床房") {
          this.formTwo.typeId = 3;
        } else if (this.RoomType == "商务套房") {
          this.formTwo.typeId = 4;
        } else {
          this.formTwo.typeId = 5;
        }
        this.openTwo = true;
        console.log(this.formTwo);
      });
      console.log(this.formOne);
    },
    // 添加入住信息并检验表单
    submitFormTwo() {
      // this.$refs.formTwo.validate((valid) => {
      //   if (valid) {
      //     this.formTwo.price = parseFloat(this.formTwo.price);
      //     enterOrder(this.formTwo).then((response) => {
      //       this.$message.success(response.msg);
      //       console.log(response.msg);
      //       this.$message.success("表单提交成功");
      //     });
      //   } else {
      //     this.$message.error("表单验证失败，请检查输入");
      //   }
      // });
      // console.log(this.formTwo);
      this.formTwo.price = parseFloat(this.formTwo.price);
      enterOrder(this.formTwo).then((response) => {
        this.$message.success("表单提交成功");
        setTimeout(() => {
          this.$message.success(response.msg);
        }, 1000);
        console.log(response.msg);
      });
    },
    // 提交数据
    submitForm() {
      endEnter().then((response) => {
        this.$message.success(response.msg);
        this.getList();
        this.cancelTwo();
      });
    },
    // 取消提交
    cancelOne() {
      this.openOne = false;
      this.resetFormOne();
    },
    cancelTwo() {
      this.openTwo = false;
      this.openOne = false;
      this.resetFormTwo();
    },

    showTable() {
      this.showTable1 = true;
      this.showTable2 = false;
    },

    // 获取房型
    getroomTypeOptions() {
      // 访问后端接口，查外键所有对象
      // 结果赋值this.roomTypeOptions
      listAllRoomType().then((response) => {
        this.roomTypeOptions = response.data;
      });
    },
    // 当下拉框选项变化时更新输入框的值
    updateInput() {
      const selectedRoomType = this.roomTypeOptions.find(
        (option) => option.typeName === this.formTwo.roomType
      );
      // 如果找到了选中的房间类型对象，则更新 typeId 输入框的值
      if (selectedRoomType) {
        this.formTwo.typeId = selectedRoomType.typeId;
      }
    },
    // 预定表格的提交
    submitFormThree() {
      // this.formThree.price = parseFloat(this.formThree.price)
      // enterOrder(this.formThree).then((response) => {
      //   this.$message.success(response.msg)
      //   console.log(response.msg)
      // })
      // console.log(this.formThree)
      console.log("提交入住表单");
    },
    cancelThree() {
      this.openThree = false;
    },

    /** 处理分页 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    // 校验表格：性别，电话号码，客户ID是身份证号码
    validateSex(rule, value, callback) {
      if (value !== "男" && value !== "女") {
        callback(new Error("请输入正确的性别(男/女)"));
      } else {
        callback();
      }
    },
    validatePhone(rule, value, callback) {
      const reg = /^[1][3,4,5,7,8][0-9]{9}$/; // 11位数的电话号码
      if (!reg.test(value)) {
        callback(new Error("请输入正确的电话号码"));
      } else {
        callback();
      }
    },
    validatorNumber(rule, value, callback) {
      const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (!reg.test(value)) {
        callback(new Error("请输入正确的身份证号码"));
      } else {
        callback();
      }
    },

    //设置退房时间设置
    outTimeDisabledDate(time) {
      // 获取入住时间
      const inTime = new Date(this.queryParams.inTime);
      // 如果入住时间为空，返回 false，即不禁用任何日期
      if (!inTime) return false;
      // 禁用入住时间之前的日期
      return time.getTime() < inTime.getTime();
    },
  },
};
</script>

<style scoped lang="scss">
</style>